package com.angular.service.impl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.angular.aspect.LoginedValidateAspect;
import com.angular.entity.ResponseBody;
import com.angular.mapper.CideUserMapper;
import com.angular.pojo.CideUser;
import com.angular.pojo.CideUserExample;
import com.angular.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	Map<String, String> sessionMap = new HashMap<String, String>();
	@Autowired
	CideUserMapper cideUserMapper;

	@Override
	public boolean isLogined(HttpServletRequest request) {
		// request.getSession().getAttribute(name);
		String sessionId = request.getSession(true).getId();
//		return false;
		return sessionMap.values().contains(sessionId);
	}

	@Override
	public ResponseBody<List<Object>> login(CideUser user,HttpServletRequest request) {
		ResponseBody<List<Object>> result=null;
		try {
			CideUserExample example=new CideUserExample();
			example.createCriteria().andAccountEqualTo(user.getAccount()).andPasswordEqualTo(user.getPassword());
			if(cideUserMapper.selectByExample(example).size()==0) {
				return new ResponseBody<List<Object>>(1, "账号或密码错误",null);
			}
			
			String sessionId = request.getSession(true).getId();
			
			sessionMap.put(user.getAccount(), sessionId);
			
			
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(
					"F:\\wkh\\resource\\web-browser\\angular2\\project\\angular-cli-project\\src\\app\\json\\wkhPermission.json")));
			String permissionJsonString = "";

			String tmpString;

			while ((tmpString = br.readLine()) != null) {
				permissionJsonString += tmpString;
			}

			br.close();
			List<Object> list = null;
			list = JSON.parseArray(permissionJsonString, Object.class);
			
			result=new ResponseBody<List<Object>>(0, null, list);
		} catch (IOException e) {
			result=new ResponseBody<List<Object>>(1, "登陆失败",null);
		}
		return result;
	}

	@Override
	public boolean updateUserByAccounts(List<String> accounts,CideUser user) {
		CideUserExample example=new CideUserExample();
		example.or().andAccountIn(accounts);
		cideUserMapper.updateByExampleSelective(user, example);
		return true;
	}

	@Override
	public boolean deleteUserByAccounts(List<String> accounts) {
		CideUser user=new CideUser();
		user.setActive(false);
		return updateUserByAccounts(accounts, user);
	}

}
